import React from 'react';
import { CHART_LINK, SCROLL_POSITION } from 'src/pages/AnalyseManage/EditReport/topics';
import PubSub from 'pubsub-js';
import { DL_TYPE, WD_TYPE } from 'src/pages/AnalyseManage/EditReport/components/EditorDataType/EnumConfig';
import { message } from 'antd';

export interface IProps {
	config: any,
	isCurrent: boolean,
	key: string;
	id: string;
	pageId: string;
	chartLayout: any;
	chartsConfig: Array<any>;
	onValuesChange: ( chartType: string, key: string, values: Object, configType: string ) => void;
	onAllValuesChange: Function;
	tenantCode?: string;
	setChaining: ( publisherId: string, isChaining: boolean ) => void;
	setDrilling: ( chartId ) => void;
	drillChartsIds: Array<string>
};

export class ChartService extends React.Component<IProps, any> {

	//	初始渲染
	initRender() {
		//	在可视区域才进行初次渲染
		if ( document.getElementById( this.props.id ).getBoundingClientRect().top < document.body.clientHeight ) {
			//	@ts-ignore
			this.initEvent && this.initEvent();
		}
	}

	//	事件监听
	addSubEvents = () => {

		//	监听拖拉拽区域的滚动事件
		const scrollPositionEventToken = PubSub.subscribe( SCROLL_POSITION, ( event, { bottom } ) => {
			//	如果图表的顶部接近容器底部+100的距离
			if ( document.getElementById( this.props.id ).getBoundingClientRect().top < bottom + 100 ) {
				//	@ts-ignore
				!this.state.isRender && this.initEvent && this.initEvent();
			}

		} );

		const token = PubSub.subscribe( CHART_LINK, ( event, {
			publisherId,
			listenerIds = [],
			dimension = [],
			tableCode = ''
		} ) => {
			//	如果发布者的id是自身，则跳过
			if ( publisherId === this.props.id ) return;

			//	如果不是监听者，则跳过
			if ( !listenerIds.includes( this.props.id ) ) return;

			//	如果tableCode不同，则跳过
			if ( tableCode !== this.props.config.data.tableCode ) return;

			this.setState( {
				dependencies: dimension
			} );

			dimension.length > 0 && this.props.setChaining( publisherId, true );
		} );

		this.setState( {
			eventToken: [ scrollPositionEventToken, token ]
		} );
	};


	//	获取字段参数，使用前，请检查是否参数是否与所需的一致
	getFieldParams( item ) {
		console.log( item );
		return {
			aggregateType: item.modelType === DL_TYPE ? item.aggregateType : '',	//	度量的聚合类型
			formatType: item.modelType === WD_TYPE ? item.formatType : '',	// 维度的聚合类型
			alias: item.title.trim(),
			dataType: item.dataType,
			frontendId: '',
			id: item.name,
			orderType: item.orderType,	//	排序方式
			quota: item.modelType === WD_TYPE ? 'WD' : 'DL',
			symbol: '',
			type: item.type,
			value: '',
			precision: item.precision,
			dataUnit: item.dataUnit
		};
	}

	//	获取下级字段信息
	getChildDimension( params ) {
		let result = [];
		params.forEach( v => {
			if ( v.children && v.children.length > 0 ) {
				result.push( v.children[ 0 ] );
			}
		} );
		return result;
	}

	//	处理下钻逻辑
	async handleDrillDown( dimension, dependencies ) {
		//	获取下一级
		const childDimension = this.getChildDimension( dimension );

		if( childDimension.length === 0 ) return message.warn( '下一层数据不存在' );

		//	下钻组装参数
		this.setState( {
			drillDownConditions: dependencies,	//	设置conditions
			drillDownDimension: childDimension	//	设置children
		} );

		//	获取数据
		//	@ts-ignore
		await this.getConditionData( childDimension );

		//	渲染
		//	@ts-ignore
		this.state.chartEl.update( this.getConfig() );

		this.props.setDrilling( this.props.id );
	}

	//	如果是日期类型，就返回日期类型，否则返回空
	isDateType = ( dataType ) => {
		const dateType = [ 'DATE', 'DATETIME', 'TIMESTAMP', 'TIME', 'YEAR' ];
		if ( dateType.some( v => v.toLowerCase() === dataType.toLowerCase() ) ) {
			return 'YEAR_QUARTERLY';
		} else {
			return '';
		}
	};

	//	清除下钻
	clearDrill() {
		[ 'drillDownConditions', 'drillDownDimension' ].forEach( v => {
			if ( this.state[ v ].length > 0 ) {
				this.setState( {
					[ v ]: []
				} );
			}

		} );
	}

	componentDidMount() {
		this.addSubEvents();
		this.initRender();

	}

	componentWillUnmount(): void {
		this.state.eventToken.forEach( token => PubSub.unsubscribe( token ) );
	}

}
